(function($) {
	$.fn.getQuery = function(options) {
		o = $.extend({
			type: 'xpath', //生成类型  'xpath' or 'selector'
			highLight: true, //选择的元素是否高亮显示
			fullPath: true, //是否是全路径
			preferenceAttr: 'id', //'id' or 'class'
		}, options || {});
		if (o.highLight) {
			this.highLight(o);
		}

		var path = getPath(this, '');
		selector = path.replaceAll('/', '>').replaceAll('\\[', ':eq(').replaceAll('\\]', ')').replaceAll(
			'\\:eq\\(\\@', '[').replaceAll('\'\\)', '\']');
		query = '/' + path;
		if (!o.fullPath) {
			query = '/' + query;
		}
		if (o.type == 'selector') {
			return selector;
		} else {
			return query;
		}
	}


	this.getXpath = function() {
		return query;
	}


	this.getSelector = function() {
		return selector;
	}


	$.fn.highLight = function(options) {
		op = $.extend({
			bgColor: 'yellow', //背景色
			border: 'yellow 1px solid', //边框
			expansion: 3, //扩大边框
		}, options || {});
		$('body').append("<div id='abs-box' class='abs'> </div>");
		$('head').append("<style>.abs{position:absolute;zoom:1;pointer-events:none;z-index:-1;}</style>");
		var div = $('#abs-box');
		if (div != this) {
			var pos = this.offset(),
				em = op.expansion;
			div.css({
				'left': pos.left - em,
				'top': pos.top - em,
				'width': this.width() + 2 * em,
				'height': this.height() + 2 * em
			});
			div.css({
				'background-color': op.bgColor,
				'border': op.border
			});
		}
	}

	function getPath(e, path) {
		var tn = e.get(0).tagName;
		if (isNullOrEmpty(e) || isNullOrEmpty(tn)) {
			return path;
		}
		var attr = getAttr(e);
		tn = tn.toLowerCase() + attr;
		path = isNullOrEmpty(path) ? tn : tn + "/" + path;
		var parentE = e.parent();
		if (isNullOrEmpty(parentE) || (!o.fullPath && attr.substring(0, 5) == '[@id=')) {
			return path;
		}
		return getPath(parentE, path);
	}


	function getAttr(e) {
		var tn = e.get(0).tagName;
		var id = e.attr('id'),
			clazz = e.attr('class');
		var hasId = !isNullOrEmpty(id),
			hasClazz = !isNullOrEmpty(clazz);
		id = "[@id='" + id + "']";
		clazz = "[@class='" + clazz + "']";
		if (hasId && hasClazz) {
			if (o.preferenceAttr.toLowerCase() == 'class') {
				return clazz;
			} else {
				return id;
			}
		} else if (hasId && !hasClazz) {
			return id;
		} else if (!hasId && hasClazz) {
			return clazz;
		} else {
			if (e.siblings(tn).size() > 0) {
				var i = e.prevAll(tn).size();
				if (o.type == 'xpath') {
					i++;
				}
				return '[' + i + ']';
			} else {
				return '';
			}
		}
	}

	function isNullOrEmpty(o) {
		return null == o || 'null' == o || '' == o || undefined == o;
	}


	/** 处理跨域访问localStorage
	  将获取到的路径传回父页面
	*/
	// window.addEventListener('storage',function(e){
	// 	console.log(e)
	//  if(window.parent){	
	// 		window.parent.postMessage(JSON.stringify(e),'*')
	// 	 }
	// },false)
})(jQuery);

String.prototype.replaceAll = function(regx, t) {
	return this.replace(new RegExp(regx, 'gm'), t);
};

function handleBind() {
	if (self != top) {
		// 处理a标签跳转问题,跳转在本页跳转
		$("a").attr("target", "_self");
		$(document).on('click', function(e) {
			e = e || window.event //获取事件对象
			let target = e.target || e.srcElement //获取事件目标
			// 判断 选取元素是否为列表的一部分
			let doms = $(target).parent().children()
			let listFlag = false
			let siblingsDom = []
			if (doms.length > 1) {
				doms.each((index, dom) => {
					siblingsDom.push(dom.tagName)
				})
				listFlag = siblingsDom.every(dom => {
					if (dom.toLowerCase() === 'script') return true
					return dom === target.tagName
				})
			} else {
				doms = $(target).parent().parent().children()
				if (doms.length > 2) {
					doms.each((index, dom) => {
						siblingsDom.push(dom)
					})
					listFlag = siblingsDom.every(dom => {
						return dom.tagName === $(target).parent()[0].tagName && dom.className == $(target).parent()[0].className
					})
					// 当父元素为选中列时，将target重新设置，为原target父元素
					if (listFlag) {
						target = $(target).parent()[0]
					}
				}
			}
			// 获取域名
			let url = target.origin + target.pathname + target.search
			// 判断为文本节点还是IMG
			let content = ''
			if (target.tagName === 'IMG') {
				content = $(target).attr('src')
			} else {
				content = $(target).text()
			}
			let selector = $(target).getQuery({
				type: 'xpath', //生成类型:  'xpath' or 'selector', 默认是'xpath'
				preferenceAttr: 'id', // 属性偏好: 'id' or 'class', 默认是id
				highLight: true, //选择的元素是否高亮显示, 默认是true
				bgColor: 'yellow', //背景色, 默认是'yellow'
				border: 'yellow 1px solid', //边框, 默认是'yellow 1px solid'
				expansion: 3, //扩大边框, 默认是3
				fullPath: true //是否是全路径, 默认是false
			})
			let msgArray = [];
			let selectorMsg = {
				"url": url,
				"xpath": selector,
				"content": content,
				"list": listFlag,
				"tagName": target.tagName
			}
			msgArray.push(selectorMsg);
			localStorage.setItem("msg", JSON.stringify(msgArray));
			window.parent.postMessage(JSON.stringify(selectorMsg), '*')
			return false;
		})
	}
}
$(document).ready(function() {
	handleBind()
});
